package com.itstyle.cloud.common.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 日志(认证)拦截器
 * 创建者 张志朋
 * 创建时间	2017年9月26日
 */
@Slf4j
public class SysInterceptor implements HandlerInterceptor {

    public String loginUrl;

    public SysInterceptor(String loginUrl) {
        this.loginUrl = loginUrl;
    }

    public static final String SESSIONKEY = "user";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {

        String token = request.getParameter("token");
        HttpSession session = request.getSession();
        Object attribute = session.getAttribute(SESSIONKEY);
        if (StringUtils.isEmpty(token) && null == attribute) {
            response.sendRedirect(this.loginUrl);
            return false;
        }

        if (StringUtils.isNotEmpty(token) && null == attribute) {
            //todo 去统一验证中心验证

            session.setAttribute(SESSIONKEY, token);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) throws Exception {

    }

}
